import Runtime from "./Runtime";

type ProgressEventCallback = (evnet: BundleProgressEvent) => void;

export default class BundleManager {

    public loadedBundles: Map<string, cc.AssetManager.Bundle> = null;

    //从runtime中加载子包
    private _runtimeJson: cc.JsonAsset = null;
    private static _bundleMgr: BundleManager = null;

    public static get bundleMgr(): BundleManager {
        if (this._bundleMgr === null) {
            this._bundleMgr = new BundleManager();

        }
        return this._bundleMgr;
    }


    /**
     * 根据json表加载子包
     * @param progress
     * @return 
     */
    public async load(progressEvent?: ProgressEventCallback) {
        // let l_bundle = await this.loadBundle(l_module);

        let promise = new Promise((resolve, reject)=>{
            // let moduleNames = Runtime.instance.getModuleNames();
            // for (let name of moduleNames) {
            //     let l_module = Runtime.instance.getModule(name);
            //     if (l_module && !this.loadedBundles.has(name)) {
            //         //  let l_bundle = await this.loadBundle(name);
            //     }
            // }
        });
        

        return promise
    }

    /**
     * 加载分包
     * @param bundleName 
     * @returns _bundleMgr
     */
    public async loadBundle(bundleName: string): Promise<cc.AssetManager.Bundle> {
        return new Promise((resolve, reject)=>{
            cc.assetManager.loadBundle(bundleName,(err: Error, bundle:cc.AssetManager.Bundle)=>{
                if (err) {
                    reject(err);
                }
                this.loadedBundles.set(bundleName, bundle);
                resolve(bundle);
            });
        });
    }
}

export class BundleProgressEvent {
    //加载进度百分比
    percentLoaded: number;
    
    //加载文件进度百分比
    percentLoadedFile: number;

    //当前加载文件数量
    loadedFiles: number;

    //总文件数量
    totalFiles: number;
}